package com.xh.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/10/24 17:39
 **/
public class JSONArrayTypeHandler extends BaseTypeHandler<JSONArray> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONArray jsonObject, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(jsonObject));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex));
    }

    private String toJson(JSONArray object) {
        try {
            return JSONObject.toJSONString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private JSONArray toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return JSON.parseArray(content);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}